package com.kc.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.kc.business.domain.order.dto.BizGoodsOrderRefundDTO;
import com.kc.business.domain.order.dto.BizOrderStatisticsDTO;
import com.kc.business.domain.order.entity.BizGoodsOrder;
import com.kc.business.domain.order.entity.BizGoodsOrderRefund;
import com.kc.business.domain.order.entity.BizOrderGoods;
import com.kc.business.domain.order.entity.BizUserAddress;
import com.kc.business.domain.order.query.BizGoodsOrderRefundQuery;
import com.kc.business.mapper.BizGoodsOrderMapper;
import com.kc.business.mapper.BizGoodsOrderRefundMapper;
import com.kc.business.mapper.BizOrderGoodsMapper;
import com.kc.business.service.IBizGoodsOrderService;
import com.kc.common.core.domain.AjaxResult;
import com.kc.common.utils.RocketMQTemplate;
import com.kc.common.utils.StringUtils;
import com.kc.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 商品订单管理service impl
 */
@Service
@Slf4j
public class BizGoodsOrderServiceImpl implements IBizGoodsOrderService {
    @Resource
    private BizGoodsOrderMapper bizGoodsOrderMapper;
    @Resource
    private BizOrderGoodsMapper bizOrderGoodsMapper;
    @Resource
    private BizGoodsOrderRefundMapper bizGoodsOrderRefundMapper;
    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 订单统计
     *
     * @param currDate
     * @return
     */
    @Override
    public BizOrderStatisticsDTO getOrderHistoryStatistics(String currDate, String endTime,Integer platformId,Integer type) {
        BizOrderStatisticsDTO bizOrderStatisticsDTO = bizGoodsOrderMapper.getOrderHistoryStatistics(currDate, endTime,platformId,type);
        if (bizOrderStatisticsDTO.getOrderTotalMoney() == null) {
            bizOrderStatisticsDTO.setOrderTotalNum(0);
            bizOrderStatisticsDTO.setOrderTotalMoney(new BigDecimal(0));
            bizOrderStatisticsDTO.setOrderAvgMoney(new BigDecimal(0));
        } else {
            bizOrderStatisticsDTO.setOrderAvgMoney(bizOrderStatisticsDTO.getOrderTotalMoney().divide(new BigDecimal(bizOrderStatisticsDTO.getOrderTotalNum()), 2, BigDecimal.ROUND_HALF_UP));
        }
        return bizOrderStatisticsDTO;
    }

    /**
     * 历史日期统计
     *
     * @param dateList
     * @return
     */
    @Override
    public List<BizOrderStatisticsDTO> getHistoryStatistics(List<String> dateList) {
        return null;
    }

    /**
     * 订单列表
     *
     * @param bizGoodsOrder
     * @return
     */
    @Override
    public List<BizGoodsOrder> getOrderList(BizGoodsOrder bizGoodsOrder) {
        Integer orderId = bizGoodsOrder.getId();
        List<BizGoodsOrder> bizGoodsOrderList = bizGoodsOrderMapper.getOrderList(bizGoodsOrder);
        bizGoodsOrderList.forEach(goodsOrder -> {
            goodsOrder.setStatusName(dictDataService.selectDictLabel("goods_order_status", goodsOrder.getStatus()));
            BizUserAddress bizUserAddress = JSONObject.parseObject(goodsOrder.getAddress(), new TypeReference<BizUserAddress>() {
            });
            goodsOrder.setUserAddress(bizUserAddress);
            BizOrderGoods bizOrderGoods = new BizOrderGoods();
            bizOrderGoods.setOrderId(goodsOrder.getId());
            if(orderId == null) {
                if (bizGoodsOrder.getStatus() == null) {
                    bizOrderGoods.setStatus(0);
                } else if (bizGoodsOrder.getStatus().equals("4")) {
                    //退款中
                    bizOrderGoods.setStatus(2);
                } else if (bizGoodsOrder.getStatus().equals("5")) {
                    bizOrderGoods.setStatus(3);
                } else {
                    bizOrderGoods.setStatus(0);
                }
            }
            List<BizOrderGoods> bizOrderGoodsList = bizOrderGoodsMapper.select(bizOrderGoods);
            bizOrderGoodsList.forEach(orderGoods -> {
                orderGoods.setStatusName(getGoodsStatusName(goodsOrder, orderGoods));
            });

            goodsOrder.setOrderGoodsList(bizOrderGoodsList);
        });
        return bizGoodsOrderList;
    }

    /**
     * 获取订单下商品状态名称
     *
     * @param goodsOrder
     * @param orderGoods
     * @return
     */
    @Override
    public String getGoodsStatusName(BizGoodsOrder goodsOrder, BizOrderGoods orderGoods) {
        //todo 判断商品状态，如果订单为已关闭，显示商品已退款，如果订单未管理判断商品状态:如果商品状态为可退款，显示订单状态，如果商品状态为退款完成显示已退款，其他显示退款中
        String statusName = "";
        if ("-1".equals(goodsOrder.getStatus())) {
            statusName = "订单已取消";
        } else {
            if (orderGoods.getStatus().equals(0)) {
                //取订单状态
                if ("3".equals(goodsOrder.getStatus())) {
                    statusName = "已确认收货";
                } else {
                    statusName = goodsOrder.getStatusName();
                }
            } else if (orderGoods.getStatus().equals(3)) {
                statusName = "已退款";
            } else {
                statusName = "退款中";
            }
        }
        return statusName;
    }

    @Override
    public BizGoodsOrder getOrderInfo(Integer orderId) {
        return bizGoodsOrderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public int updateOrderById(BizGoodsOrder bizGoodsOrder) {
        return bizGoodsOrderMapper.updateByPrimaryKeySelective(bizGoodsOrder);
    }


    /**
     * 更改订单
     * @param bizGoodsOrder
     * @return
     */
    @Override
    public Integer updateOrder(BizGoodsOrder bizGoodsOrder) {
        return bizGoodsOrderMapper.updateByPrimaryKey(bizGoodsOrder);
    }

    @Override
    public Integer getNoSendOut(Integer platformId, Integer platformType) {
        BizGoodsOrder bizGoodsOrder = new BizGoodsOrder();
        bizGoodsOrder.setMerchid(platformId);
        bizGoodsOrder.setGoodsType(platformType);
        bizGoodsOrder.setStatus("0");
        Integer goodsNum = bizGoodsOrderMapper.selectCount(bizGoodsOrder);
        return goodsNum == null ? 0 : goodsNum;
    }

    @Override
    public Integer getNoRefund(Integer platformId, Integer platformType) {
        BizGoodsOrderRefund bizGoodsOrderRefund = new BizGoodsOrderRefund();
        bizGoodsOrderRefund.setMerchid(platformId);
        bizGoodsOrderRefund.setMerchType(3);
        bizGoodsOrderRefund.setStatus(0);
        Integer num = bizGoodsOrderRefundMapper.selectCount(bizGoodsOrderRefund);
        return num == null ? 0 : num;
    }

    /**
     * 商品订单退款列表
     *
     * @param bizGoodsOrderRefundDTO
     * @return
     */
    @Override
    public List<BizGoodsOrderRefundDTO> getRefundList(BizGoodsOrderRefundDTO bizGoodsOrderRefundDTO) {
        System.out.println(bizGoodsOrderRefundDTO);
        List<BizGoodsOrderRefundDTO> bizGoodsOrderRefundDTOList = bizGoodsOrderRefundMapper.getList(bizGoodsOrderRefundDTO);
        bizGoodsOrderRefundDTOList.forEach(goodsOrderRefundDTO -> {
            if (StringUtils.isNotEmpty(goodsOrderRefundDTO.getRefundImage())) {
                String[] arr = StringUtils.split(goodsOrderRefundDTO.getRefundImage(), ",");
                goodsOrderRefundDTO.setRefundImageList(Arrays.asList(arr));
            }
        });
        return bizGoodsOrderRefundDTOList;
    }

    /**
     * 获取退款详情
     * @param id
     * @return
     */
    @Override
    public BizGoodsOrderRefundDTO getRefundInfo(Integer id) {
        BizGoodsOrderRefundDTO bizGoodsOrderRefund = bizGoodsOrderRefundMapper.getInfo(id);
        if(StringUtils.isEmpty(bizGoodsOrderRefund.getNickname())){
            bizGoodsOrderRefund.setNickname("");
        }
        //计算毫秒
        if((bizGoodsOrderRefund.getCloseDate().compareTo(DateUtil.now())) >= 1) {
            bizGoodsOrderRefund.setCloseDateMs(DateUtil.betweenMs(DateUtil.date(), DateUtil.parse(bizGoodsOrderRefund.getCloseDate())));
        }
        //处理进度条
        Integer orderProgress = 2;
        if(bizGoodsOrderRefund.getRefundType().equals(1)){
            //仅退款
            if(bizGoodsOrderRefund.getStatus().equals("1")){
                orderProgress = 3;
            }

        }else{
            orderProgress = 1;
            //退货退款
            if(bizGoodsOrderRefund.getStatus().equals("4")){
                orderProgress = 2;
            }else if(bizGoodsOrderRefund.getStatus().equals("6")){
                orderProgress = 3;
            }else if(bizGoodsOrderRefund.getStatus().equals("7")){
                orderProgress = 4;
            }else if(bizGoodsOrderRefund.getStatus().equals("1")){
                orderProgress = 5;
            }
        }
        bizGoodsOrderRefund.setOrderProgress(orderProgress);
        bizGoodsOrderRefund.setSalePrice(bizGoodsOrderRefund.getGoodsPrice().divide(new BigDecimal(bizGoodsOrderRefund.getGoodsNum().toString()),2,BigDecimal.ROUND_HALF_UP));
        return bizGoodsOrderRefund;
    }

    /**
     * 退款审核
     *
     * @param bizGoodsOrderRefundQuery
     * @return
     */
    @Override
    public AjaxResult orderRefundCheck(BizGoodsOrderRefundQuery bizGoodsOrderRefundQuery) {
        //0/申请 1/通过(退款完成，终结状态)  4/通过申请（需寄回商品）5/退款中 -1/驳回 -2/客户取消
        BizGoodsOrderRefund bizGoodsOrderRefund = new BizGoodsOrderRefund();
        bizGoodsOrderRefund.setId(bizGoodsOrderRefundQuery.getId());
        bizGoodsOrderRefund = bizGoodsOrderRefundMapper.selectByPrimaryKey(bizGoodsOrderRefund);
        if (bizGoodsOrderRefundQuery.getStatus().equals(-1)) {
            if (bizGoodsOrderRefundQuery.getRefuseDetails() != null) {
                bizGoodsOrderRefund.setRefuseDetails(bizGoodsOrderRefundQuery.getRefuseDetails());
            }
            bizGoodsOrderRefund.setRefuseRefundReason(Integer.parseInt(bizGoodsOrderRefundQuery.getRefuseRefundReason()));
        }
        if (bizGoodsOrderRefundQuery.getStatus().equals(7)) {
            if (!bizGoodsOrderRefund.getStatus().equals(6)) {
                return AjaxResult.error("参数错误");
            }
            //todo 此处需要处理退款流程
            //发生延迟队列，退款处理
            //rocketMQTemplate.sendDelayMessage("goods_order_refund_auto_check",bizGoodsOrderRefund,300);
        }
        bizGoodsOrderRefund.setStatus(bizGoodsOrderRefundQuery.getStatus());
        return AjaxResult.success(bizGoodsOrderRefundMapper.updateByPrimaryKey(bizGoodsOrderRefund));
    }


}
